from PIL import Image, ImageTk
import customtkinter as CTk
from CTkMessagebox import CTkMessagebox
import os
import time
import random
import commands
from settings import MainWindow
import stt
import asist
import threading
import json


try:
    with open("settings.json", "r") as f:
        sett = json.load(f)
        CTk.set_appearance_mode(sett["appearance_mode"])
        CTk.set_default_color_theme(sett["default_color_theme"])
except FileNotFoundError:
    CTk.set_appearance_mode("light")
    CTk.set_default_color_theme("blue")
    sett = {
        "family": "Helvetica",
        "size": 24,
    }

wallpapers = os.listdir("image/wallpaper")
wallpaper = os.path.join("image/wallpaper", random.choice(wallpapers))

class InputWindow(CTk.CTkToplevel):
    def __init__(self):
        super().__init__()
        self.overrideredirect(True)
        self.font = CTk.CTkFont(family=sett["family"], size=sett["size"])

        self.title("Ввод парольной фразы")
        self.password_info = CTk.CTkLabel(self, text="Необходимо задать пароль, чтобы при необходимости его произнести для доступа к некоторому функционалу.", wraplength=350)
        self.password_info.configure(font=("Helvetica", 24))
        self.password_info.pack(pady=10)

        self.input_label1 = CTk.CTkLabel(self, text="Введите пароль:")
        self.input_label1.configure(font=("Helvetica", 24))
        self.input_label1.pack(pady=5)

        self.password_entry1 = CTk.CTkEntry(self, show="*", width=200, font=("Arial Unicode MS", 12))
        self.password_entry1.configure(font=("Helvetica", 24))
        self.password_entry1.pack(pady=5)

        self.input_label2 = CTk.CTkLabel(self, text="Повторите пароль:")
        self.input_label2.configure(font=("Helvetica", 24))
        self.input_label2.pack(pady=5)

        self.password_entry2 = CTk.CTkEntry(self, show="*", width=200, font=("Arial Unicode MS", 12))
        self.password_entry2.configure(font=("Helvetica", 24))
        self.password_entry2.pack(pady=5)

        self.save_button = CTk.CTkButton(self, text="Сохранить", command=self.confirm_password)
        self.save_button.configure(font=("Helvetica", 24))
        self.save_button.pack(pady=10)

        self.voice_button = CTk.CTkButton(self, text="Голосовой ввод", command=self.get_password)
        self.voice_button.configure(font=("Helvetica", 24))
        self.voice_button.pack(pady=10)

        self.protocol("WM_DELETE_WINDOW", self.on_close)
        self.grab_set()
    def confirm_password(self):
        password1 = self.password_entry1.get().lower()
        password2 = self.password_entry2.get().lower()

        if len(password1) < 8 or len(password2) < 8:
            CTkMessagebox(title="Ошибка",
                          message="Пароль должен быть не менее 8 символов!",
                          icon="cancel",
                          option_1="Попробовать еще раз")
            return
        if password1 == password2:
            self.save_settings()
            CTkMessagebox(title="Успех",
                          message="Пароль сохранен!",
                          icon="check",
                          option_1="OK")
        else:
            CTkMessagebox(title="Ошибка",
                          message="Пароли не совпадают!",
                          icon="cancel",
                          option_1="Попробовать еще раз")
        time.sleep(0.3)

    def on_close(self):
        self.grab_release()
        self.destroy()

    def get_password(self):
        pass
    def save_text(self):
        self.password_variable = self.input_entry.get()

        self.destroy()
    def save_settings(self):
        sett["password"] = self.password_entry1.get().lower()
        print(sett["password"])
        with open("settings.json", "w", encoding="cp1251") as f:
            json.dump(sett, f, ensure_ascii=False)
        self.grab_release()
        self.destroy()



class App(CTk.CTk):
    def __init__(self):
        super().__init__()

        self.geometry("800x700")
        self.title("Загрузка...")
        self.wm_iconbitmap()
        icopath = ImageTk.PhotoImage(file="image/micro.png")
        self.iconphoto(False, icopath)

        width = 800
        height = 700
        spawn_x = int((self.winfo_screenwidth() - width) / 2)
        spawn_y = int((self.winfo_screenheight() - height) / 2)

        self.geometry(f"{width}x{height}+{spawn_x}+{spawn_y}")

        self.background_image = CTk.CTkImage(dark_image=Image.open(wallpaper), size=(1000, 1000))
        self.background_img_lb = CTk.CTkLabel(master=self, text="", image=self.background_image)
        self.background_img_lb.place(relx=0.5, rely=0.5, anchor='center')

        transparent_image = Image.new('RGBA', (1000, 1000), (255, 255, 255, 0))
        transparent_photo = ImageTk.PhotoImage(transparent_image)

        frame = CTk.CTkFrame(self)
        frame.place(relx=0.5, rely=0.5, anchor='center')

        self.label = CTk.CTkLabel(frame, text='')
        self.label.pack()

        self.progress_bar = CTk.CTkProgressBar(frame, width=600)

        self.progress_bar.pack()
        self.progress_bar.set(0)

        self.update_progress()

    def update_progress(self):
        def close_and_quit():
            self.after(100, self.withdraw())
            self.after(200, self.quit)
            self.open_new_window()
        while True:
            value = self.progress_bar.get() * 100
            if value < 100:
                increment = random.randint(5, 15)
                new_value = min(value + increment, 100)
                self.progress_bar.set(new_value / 100)
                self.label.configure(text=f'Loading... {new_value}%')
                self.update()
            else:
                self.label.configure(text='Done')
                self.progress_bar.stop()
                self.after(1000, close_and_quit)
                time.sleep(1)
                break
            time.sleep(0.1)

    def open_new_window(self):
        new_window = MainWindow(sett)
        new_window.title("Голосовой помощник")
        new_window.geometry("800x800")
        new_window.attributes("-topmost", True)
        width = 800
        height = 800
        spawn_x = int((new_window.winfo_screenwidth() - width) / 2)
        spawn_y = int((new_window.winfo_screenheight() - height) / 2)

        new_window.geometry(f"{width}x{height}+{spawn_x}+{spawn_y}")

        stop_event = threading.Event()

        def va_listen_thread(new_window):
            stt.va_listen(asist.va_respond, new_window)
        def check_input_window():
            while True:
                stop_event.wait()
                if not input_window.winfo_exists():
                    self.after(0, new_window.deiconify)

                    self.after(500, lambda: commands.wish_me(new_window))
                    commands.wish_me(new_window)
                    thread_va_listen = threading.Thread(target=va_listen_thread, args=(new_window,))
                    thread_va_listen.start()
                    break
                time.sleep(0.01)

        if sett["password"]=="":

            input_window = InputWindow()
            new_window.attributes("-topmost", False)
            input_window.attributes("-topmost", True)
            spawn_x1 = int((input_window.winfo_screenwidth() - 400) / 2)
            spawn_y1 = int((input_window.winfo_screenheight() - 400) / 2)
            input_window.geometry(f"{400}x{400}+{spawn_x1}+{spawn_y1}")

            check_thread = threading.Thread(target=check_input_window)
            check_thread.start()
            stop_event.set()
            input_window.attributes("-topmost", True)

        else:
            commands.wish_me(new_window)
            thread_va_listen = threading.Thread(target=va_listen_thread, args=(new_window,))
            thread_va_listen.start()
            #stt.va_listen(asist.va_respond, new_window)

        new_window.mainloop()


if __name__ == "__main__":
    app = App()
    app.mainloop()
